import { Player } from "@minecraft/server";
import { Game } from "@sapi-game/main";
import { parkourGameModule } from "@/parkour/module";
import { ParkourGame } from "@/parkour/parkourGame";

export class PKEndState extends parkourGameModule.State {
    override onEnter(): void {
        this.runner.run(async (r) => {
            this.judge({
                blue: this.context.blue.score,
                red: this.context.red.score,
            });
            await r.wait(80);
            await r.do(() => {
                Game.manager.stopGame(ParkourGame);
            });
        });
    }

    judge({ blue, red }: { blue: number; red: number }) {
        const outcomes = {
            blue: {
                text: "§b蓝队胜利",
                msg: "§a恭喜你获胜了",
                op: ">",
                team: this.context.blue.team,
            },
            red: {
                text: "§c红队胜利",
                msg: "§a恭喜你获胜了",
                op: "<",
                team: this.context.red.team,
            },
            draw: {
                text: "§e平局",
                msg: "",
                op: "=",
                team: undefined,
            },
        };

        let result: (typeof outcomes)[keyof typeof outcomes];

        if (blue > red) {
            result = outcomes.blue;
            result.team.sendMessage(result.msg);
            result.team.forEach((p) => this.genFireWorks(p.player));
        } else if (red > blue) {
            result = outcomes.red;
            result.team.sendMessage(result.msg);
            result.team.forEach((p) => this.genFireWorks(p.player));
        } else {
            result = outcomes.draw;
        }

        this.context.groupSet.runCommand(
            `title @s subtitle §b${blue} §r${result.op} §c${red}`
        );
        this.context.groupSet.runCommand(`title @s title ${result.text}`);
    }

    genFireWorks(player: Player) {
        this.runner.run(async (r) => {
            r.do(() =>
                player.dimension.spawnEntity(
                    "minecraft:fireworks_rocket",
                    player.location
                )
            );
            await r.wait(10);
            r.do(() =>
                player.dimension.spawnEntity(
                    "minecraft:fireworks_rocket",
                    player.location
                )
            );
            await r.wait(10);
            r.do(() =>
                player.dimension.spawnEntity(
                    "minecraft:fireworks_rocket",
                    player.location
                )
            );
        });
    }
}
